import api from './api.js';

document.addEventListener('DOMContentLoaded', () => {
    // DOM元素
    const loginForm = document.getElementById('login-form');
    const registerForm = document.getElementById('register-form');
    const authButtons = document.getElementById('auth-buttons');
    const userMenu = document.getElementById('user-menu');
    const logoutBtn = document.getElementById('logout-btn');
    const tabButtons = document.querySelectorAll('.tab-btn');
    const loginError = document.getElementById('login-error');
    const registerError = document.getElementById('register-error');
    
    // 初始化检查登录状态
    checkAuthStatus();
    
    // 标签页切换
    tabButtons.forEach(btn => {
        btn.addEventListener('click', function() {
            switchTab(this.dataset.tab);
        });
    });
    
    // 登录表单提交
    if (loginForm) {
        loginForm.addEventListener('submit', async (e) => {
            e.preventDefault();
            await handleLogin();
        });
    }
    
    // 注册表单提交
    if (registerForm) {
        registerForm.addEventListener('submit', async (e) => {
            e.preventDefault();
            await handleRegister();
        });
    }
    
    // 退出登录
    if (logoutBtn) {
        logoutBtn.addEventListener('click', handleLogout);
    }
    
    // 切换标签页函数
    function switchTab(tabId) {
        // 更新活动标签
        tabButtons.forEach(b => b.classList.remove('active'));
        document.querySelector(`.tab-btn[data-tab="${tabId}"]`).classList.add('active');
        
        // 显示对应表单
        document.querySelectorAll('.auth-form').forEach(form => {
            form.classList.remove('active');
        });
        document.getElementById(`${tabId}-form`).classList.add('active');
    }
    
    // 登录处理函数
    async function handleLogin() {
        const username = document.getElementById('login-username').value;
        const password = document.getElementById('login-password').value;
        
        try {
            const response = await api.post('/auth/login', {
                username,
                password
            });
            
            loginError.textContent = '';
            showToast('登录成功！', 'success');
            
            // 更新UI并跳转
            updateAuthUI(response);
            setTimeout(() => {
                window.location.href = 'menu.html';
            }, 1000);
        } catch (error) {
            console.error('登录错误:', error);
            loginError.textContent = error.message || '登录失败，请检查用户名和密码';
        }
    }
    
    // 注册处理函数
    async function handleRegister() {
        const username = document.getElementById('register-username').value;
        const email = document.getElementById('register-email').value;
        const password = document.getElementById('register-password').value;
        const confirm = document.getElementById('register-confirm').value;
        
        // 验证密码匹配
        if (password !== confirm) {
            registerError.textContent = '两次输入的密码不匹配';
            return;
        }
        
        try {
            const response = await api.post('/auth/register', {
                username,
                email,
                password
            });
            
            registerError.textContent = '';
            showToast('注册成功，请登录', 'success');
            
            // 切换到登录标签并填充用户名
            switchTab('login');
            document.getElementById('login-username').value = username;
            document.getElementById('login-password').focus();
        } catch (error) {
            console.error('注册错误:', error);
            registerError.textContent = error.message || '注册失败，请稍后再试';
        }
    }
    
    // 退出处理函数
    async function handleLogout() {
        try {
            await api.post('/auth/logout', {});
            localStorage.removeItem('user');
            updateAuthUI(null);
            showToast('已退出登录', 'info');
            window.location.href = 'index.html';
        } catch (error) {
            console.error('退出错误:', error);
            showToast('退出失败', 'error');
        }
    }
    
    // 检查认证状态
    async function checkAuthStatus() {
        try {
            const user = await api.checkAuth();
            if (user) {
                localStorage.setItem('user', JSON.stringify(user));
                updateAuthUI(user);
                
                // 如果已登录，跳转到菜单页
                if (window.location.pathname.endsWith('index.html')) {
                    window.location.href = 'menu.html';
                }
            }
        } catch (error) {
            console.error('检查认证状态错误:', error);
        }
    }
    
    // 更新认证UI
    function updateAuthUI(user) {
        if (user) {
            if (authButtons) authButtons.style.display = 'none';
            if (userMenu) {
                userMenu.style.display = 'flex';
                document.getElementById('username-display').textContent = user.username;
            }
        } else {
            if (authButtons) authButtons.style.display = 'flex';
            if (userMenu) userMenu.style.display = 'none';
        }
    }
    
    // 显示提示消息
    function showToast(message, type = 'info') {
        const toast = document.createElement('div');
        toast.className = `toast toast-${type}`;
        toast.textContent = message;
        document.body.appendChild(toast);
        
        setTimeout(() => {
            toast.classList.add('fade-out');
            setTimeout(() => {
                toast.remove();
            }, 300);
        }, 3000);
    }
});